//
//  BCTextField.m
//  BCTextFiled
//
//  Created by Billy on 15/10/21.
//  Copyright © 2015年 zzjr. All rights reserved.
//

#import "BCTextField.h"

@interface BCTextField ()

@property (nonatomic, copy) NSString *previousContent; //用户输入的正确的内容

@end

@implementation BCTextField

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    
    if (self) {

        [self addTarget:self action:@selector(formatInput:) forControlEvents:UIControlEventEditingChanged];
        [self setClearButtonMode:UITextFieldViewModeWhileEditing];
    }
    
    return self;
}

- (void)setRegx:(NSString *)regx {
    
    if (regx) {
        
        _regx = regx;
    }
}

#pragma mark - handle user typing

- (void) formatInput: (BCTextField *)textField {
    
    if (self.regx) {
        
        if ([textField.text isEqualToString:@""]) { // 用户按clear button的时候是会触发editing事件的
            
            return;
        }
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", self.regx];
    
        if ([predicate evaluateWithObject:textField.text]) { //输入是对的，把输的值保存起来
            
            self.previousContent = textField.text;
        }else { //错了后只显示原来输的正确的内容
            
            textField.text = self.previousContent ;
        }
    }
   }

#pragma mark - control placeholder
// 颜色 字体大小等
- (void) drawPlaceholderInRect:(CGRect)rect {
    
    [[UsefulUtil colorWithHexString:@"#c7c7cd"] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:15.0]];
}

//// 输入文字显示的位置
//- (CGRect) textRectForBounds:(CGRect)bounds {
//
//    CGRect inset = CGRectMake(bounds.origin.x , bounds.origin.y + bounds.size.height*1/3, bounds.size.width - MULTIPLYWIDTH(10.0), bounds.size.height);
//
//    return inset;
//}

- (CGRect) placeholderRectForBounds:(CGRect)bounds {
    
    CGRect inset = CGRectMake(bounds.origin.x , bounds.origin.y + bounds.size.height*1/3 -1, bounds.size.width - MULTIPLYWIDTH(10.0), bounds.size.height);
    
    return  inset;
}

//控制编辑文本的位置
-(CGRect)editingRectForBounds:(CGRect)bounds {
    
    return [super editingRectForBounds:bounds];;
}
@end
